package com.hzit.exception;

import com.hzit.entity.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：全局异常处理 + 结合JSR303进行数据验证
 */
// @ControllerAdvice
// @ResponseBody
@RestControllerAdvice
public class MyValidatorExceptionHandler {

	//1. 处理的是MethodArgumentNotValidException异常
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public R errorHandler(MethodArgumentNotValidException ex) {
		Map<String, String> errors = new HashMap<>();
		BindingResult result = ex.getBindingResult();
		List<FieldError> fieldErrors = result.getFieldErrors();
		for (FieldError fieldError : fieldErrors) {
			String field = fieldError.getField();
			errors.put(field, fieldError.getDefaultMessage());
		}
		return R.error().put("errors", errors);
	}

	//2. 最后，处理所有的其它异常
	@ExceptionHandler(Throwable.class)
	public R errorThrowable(Throwable t){
		String msg = "未知异常！";
		if(t != null){
			msg = t.getMessage();
		}
		return R.error().put("errors",msg);
	}
}
